﻿using System;
using log4net;
using Sherwood.Security;
using Sherwood.Web;

namespace Sherwood.Content.SearchClient
{
    /// <summary>
    /// Provides a simple way of signing a search request
    /// </summary>
    public class ClientSignedSearchClient : SearchClientBase
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(ClientSignedSearchClient));

        private Rsa _rsa;

        public ClientSignedSearchClient(string searchServiceUrl, string clientId, string privateKey)
            : base(searchServiceUrl)
        {
            ClientId = clientId;
            SetPrivateKey(privateKey);
        }

        public ClientSignedSearchClient(string searchServiceUrl) : base(searchServiceUrl)
        {
        }

        public string ClientId { get; set; }

        public void SetPrivateKey(string privateKey)
        {
            _rsa = Rsa.FromPrivateKey(privateKey);
        }

        public override void PrepareSearchRequest(QueryParameterCollection queryParameters)
        {
            if(_rsa == null)
                throw new InvalidOperationException("PrivateKey not set");

            queryParameters.Add("client", ClientId);
            queryParameters.Add("timestamp", DateTime.UtcNow);

            var signature = _rsa.SHA1Sign(queryParameters.ToString());
            if (Log.IsDebugEnabled)
                Log.DebugFormat("Signature for {0} is {1}", queryParameters, signature);
            queryParameters.Add("signature", signature);
        }
    }
}
